package response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

@WebServlet("/file")
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取相应对象的字节输出流
        OutputStream os = resp.getOutputStream();

        //返回的文件类型：1.图片 2.
        String type = req.getParameter("type");
        //返回时的操作：1.渲染 2.下载
        String show = req.getParameter("show");

        File file = null;

        if("photo".equals(type)){//返回图片
            if("1".equals(show)){
                resp.setContentType("image/jpeg");//jpg格式
            }else{
                resp.setContentType("application/octet-stream");
            }
            file = new File("D:\\JavaWeb\\img\\dog.jpg");
        }else if("music".equals(type)){//返回音乐
            if("1".equals(show)){
                resp.setContentType("audio/mp3");//MP3格式
            }else{
                //这样只是没有设置下载的文件名，有兴趣可以自行扩展完成
                resp.setContentType("application/octet-stream");
            }
            file = new File("D:\\CloudMusic\\王巨星 - 拾忆（抖音版）.mp3");
        }//其他格式就需要自行扩展了
        //返回一个文件类型：要设置Content-Length,body
        byte[] data =  Files.readAllBytes(file.toPath());
        resp.setContentLength(data.length);//=setHeader("Content-Length",xxx)
        os.write(data);
    }
}
